package com.lungle.warmdiary.app.view.me;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppConstant;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.exception.ApiErrorHelper;
import com.lungle.warmdiary.app.api.exception.ApiException;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseActivity;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.request.LoginPost;
import com.lungle.warmdiary.app.model.request.RegisterPost;
import com.lungle.warmdiary.app.model.response.Token;
import com.lungle.warmdiary.app.model.response.User;
import com.lungle.warmdiary.app.ui.InputIArrowView;
import com.lungle.warmdiary.app.ui.InputItemView;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.utils.StringUtils;
import com.lungle.warmdiary.app.utils.TDevice;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.lungle.warmdiary.app.view.MainActivity;
import com.umeng.analytics.MobclickAgent;

import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private static final String REGISTER_SCREEN = "register screen";
    @Bind(R.id.itv_username)
    InputItemView mItvUsername;
    @Bind(R.id.itv_pwd)
    InputItemView mItvPwd;
    @Bind(R.id.itv_verify_pwd)
    InputItemView mItvVerifyPwd;
    @Bind(R.id.et_capture)
    EditText mEtPhone;
    @Bind(R.id.btn_captcha)
    Button mBtnCaptcha;
    @Bind(R.id.itv_capture)
    InputItemView mItvCapture;
    @Bind(R.id.itv_email)
    InputItemView mItvEmail;
    @Bind(R.id.iav_gender)
    InputIArrowView mIavGender;
    @Bind(R.id.irv_birth)
    InputIArrowView mIrvBirth;
    @Bind(R.id.itv_qq)
    InputItemView mItvQQ;
    @Bind(R.id.itv_invest)
    InputItemView mItvInvest;
    @Bind(R.id.cb_agree)
    CheckBox mCbAgree;
    @Bind(R.id.tv_agreement)
    TextView mTvAgreement;
    @Bind(R.id.btn_register)
    Button mBtnRegister;

    @Override
    protected boolean hasBackButton() {
        return true;
    }

    @Override
    protected boolean hasActionBar() {
        return super.hasActionBar();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }


    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(REGISTER_SCREEN);
        MobclickAgent.onResume(this);

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(REGISTER_SCREEN);
        MobclickAgent.onPause(this);

    }


    private boolean prepareRegister(User user, String verifyPwd) {
        if (TextUtils.isEmpty(user.getUsername())) {
            mItvUsername.setErrorTip("未填写");
            return false;
        }

        if (!StringUtils.checkUsername(user.getUsername())) {
            mItvUsername.setErrorTip("含有非法字符");
            return false;
        }

        if (checkPassword(user, verifyPwd)) return false;


        if (checkPhone(user)) return false;

        if ((TextUtils.isEmpty(user.getVerifyCode()))) {
            mItvCapture.setErrorTip("未填写");
            return false;
        }

        if (checkEmail(user)) return false;

//        if (user.getGender() == -1) {
//            mIavGender.setErrorTip("未选择");
//            return false;
//        }

//        if (TextUtils.isEmpty(user.getBirthday())) {
//            mIrvBirth.setErrorTip("未填写");
//            return false;
//        }


//        if (!TextUtils.isEmpty(user.getQq()) && !StringUtils.isQQ(user.getQq())) {
//            mItvQQ.setErrorTip("非法QQ");
//            return false;
//        }

        if (!mCbAgree.isChecked()) {
            AppContext.showToast("请先同意服务协议");
            return false;
        }


        return true;

    }

    private boolean checkEmail(User user) {

        if (!TextUtils.isEmpty(user.getEmail()) && !StringUtils.isEmail(user.getEmail())) {
            mItvEmail.setErrorTip("邮箱格式错误");
            return true;
        }
        return false;
    }

    private boolean checkPhone(User user) {
        if (TextUtils.isEmpty(user.getCellphone())) {
            AppContext.showToast("手机号未填写");
            return true;
        }
        if (!StringUtils.isPhone(user.getCellphone())) {
            AppContext.showToast("非法手机号");
            return true;
        }
        return false;
    }

    private boolean checkPassword(User user, String verifyPwd) {
        if (TextUtils.isEmpty(user.getPassword())) {
            mItvPwd.setErrorTip("未填写");
            return true;
        }
        if (user.getPassword().length() < 6) {
            mItvPwd.setErrorTip("输入格式错误");
            return true;
        }
        if (user.getPassword().length() > 12) {
            mItvPwd.setErrorTip("输入格式错误");
            return true;
        }
        if (!StringUtils.isSafePwd(user.getPassword())) {
            mItvPwd.setErrorTip("输入格式错误");
            return true;
        }

        if (TextUtils.isEmpty(verifyPwd)) {
            mItvVerifyPwd.setErrorTip("未填写");
            return true;
        }

        if (!user.getPassword().equals(verifyPwd)) {
            mItvVerifyPwd.setErrorTip("密码不一致");
            return true;
        }
        return false;
    }

    private boolean checkAgreen() {
        if (!mCbAgree.isChecked()) {
            return false;
        }
        return true;
    }

    private void register(final User user) {
        showWaitDialog("正在注册");
        RegisterPost post = new RegisterPost(user);
        ApiFactory.getBaseApi().register(post).flatMap(tokenResult -> {
            if (tokenResult.isOk()) {
                LoginPost loginPost = new LoginPost(user.getUsername(), user.getPassword());
                LogUtils.printLogD("ApiFactory.getBaseApi().login(loginPost)");
                return ApiFactory.getBaseApi().login(loginPost);
            } else {
                LogUtils.printLogD(" Observable.error");

                return Observable.error(new ApiException(tokenResult.getCode(), tokenResult.getMsg()));
            }
        }).compose(resultObservable -> resultObservable).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<Token>>(this) {
                    @Override
                    public void onNext(Result<Token> tokenResult) {
                        super.onNext(tokenResult);


//                        CommonDialog dialog = new CommonDialog(RegisterActivity.this);
//                        dialog.setMessage(getResources().getString(R.string.dialog_register));
//                        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                            @Override
//                            public void onClick(DialogInterface arg0, int arg1) {
//                                Token token = tokenResult.getData();
//                                AppContext.getInstance().setLoginUid(token.getUserid());
//                                AppContext.getInstance().setToken(token.getToken());
//                                EventBus.getDefault().post(new UserChangeEvent());
//                                UIHelper.showMain(RegisterActivity.this, MainActivity.ACTION_REDIRECT_DEFALULT);
//                                hideWaitDialog();
//                                finish();
//                                dialog.dismiss();
//                            }
//                        });
//
//                        dialog.show();


//                        AppContext.showToast("注册成功");
//                        UIHelper.showMsg(RegisterActivity.this,getResources().getString(R.string.dialog_register));
//                        AppContext.getInstance().setProperty("user.username", user.getUsername());
//                        UIHelper.showMain(RegisterActivity.this, MainActivity.ACTION_REDIRECT_DEFALULT);


                        Token token = tokenResult.getData();
                        AppContext.getInstance().setLoginUid(token.getUserid());
                        AppContext.getInstance().setToken(token.getToken());
//
                        UIHelper.showMain(RegisterActivity.this, MainActivity.ACTION_REDIRECT_DEFALULT);

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        super.onError(e);
                        if (e instanceof ApiException) {
                            ApiException apiException = (ApiException) e;
                            if (!TextUtils.isEmpty(apiException.getExtendErrorMsg())) {
                                String errorMsg = apiException.getExtendErrorMsg();
                                ApiErrorHelper.showErrorDetail(errorMsg);
                            } else {
                                AppContext.showToast(apiException.getMessage());
                            }

                        } else {
                            AppContext.showToast("注册失败");
                        }


                    }
                });


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setActionBarTitle(R.string.actionbar_title_register);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_captcha, R.id.iav_gender, R.id.irv_birth, R.id.cb_agree, R.id.tv_agreement, R.id.btn_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_captcha:
                if (mEtPhone.getText().toString().isEmpty()) {
                    AppContext.showToast("手机号为空");
                    mEtPhone.requestFocus();
                    return;
                }
                if (!TDevice.hasInternet()) {
                    AppContext.showToast("无网络");
                    return;
                }
                getCapture(mEtPhone.getText().toString());
                break;
            case R.id.iav_gender:
                TDevice.hideSoftKeyboard(view);
                graderSelect();
                break;
            case R.id.irv_birth:
                TDevice.hideSoftKeyboard(view);
                birthSelect();
                break;
            case R.id.tv_agreement:
                UIHelper.openBrowser(this, AppConstant.URL_AGREENMENT);
                break;
            case R.id.btn_register:
                String username = mItvUsername.getInputText();
                String pwd = mItvPwd.getInputText();
                String verifyPwd = mItvVerifyPwd.getInputText();
                String phone = mEtPhone.getText().toString();
                String verifyCode = mItvCapture.getInputText();
                String gender = mIavGender.getInputText();
                String birth = mIrvBirth.getInputText();
                String qq = mItvQQ.getInputText();
                String email = mItvEmail.getInputText();
                String code = mItvInvest.getInputText();

                User user = new User();
                user.setUsername(username);
                user.setPassword(pwd);
                user.setVerifyCode(verifyCode);
                user.setCellphone(phone);
                if (TextUtils.isEmpty(gender)) {
//                    user.setGender(-1);
                } else if (gender.equals("男")) {
                    user.setGender(User.CODE_MALE);
                } else if (gender.equals("女")) {
                    user.setGender(User.CODE_FAMALE);
                }
                if (!TextUtils.isEmpty(birth))
                    user.setBirthday(birth);
                if (!TextUtils.isEmpty(qq))
                    user.setQq(qq);
                if (!TextUtils.isEmpty(email))
                    user.setEmail(email);
                if (!TextUtils.isEmpty(code))
                    user.setInviteCode(code);

                if (prepareRegister(user, verifyPwd) && checkAgreen()) {
                    if (!TDevice.hasInternet()) {
                        AppContext.showToast("无网络");
                        return;
                    }
                    register(user);

                }
                break;
        }
    }


    private void birthSelect() {
        DatePicker picker = new DatePicker(this, DatePicker.YEAR_MONTH_DAY);
        picker.setRange(1900, Calendar.getInstance().get(Calendar.YEAR));
        picker.setSelectedItem(1980, 1, 1);
        picker.setOnDatePickListener((DatePicker.OnYearMonthDayPickListener) (year, month, day) -> {
            mIrvBirth.setText(String.format("%s-%s-%s", year, month, day));
            mIrvBirth.setErrorTip("");
        });

        picker.show();
    }

    private void graderSelect() {
        final String[] sex = {"男", "女"};
        new AlertView(null, null, "取消", null, sex,
                this, AlertView.Style.ActionSheet, new OnItemClickListener() {
            public void onItemClick(Object o, int position) {
                if (position == -1) return;
                mIavGender.setText(sex[position]);
                mIavGender.setErrorTip("");
            }
        }).show();
    }

    private void getCapture(String phone) {
        showWaitDialog("获取中");
        ApiFactory.getBaseApi().getCapture(phone, 1).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(RegisterActivity.this) {

                    @Override
                    public void onCompleted() {
                        hideWaitDialog();
                        timer.start();
                        mItvCapture.requestFocus();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        super.onError(e);
                    }
                });


    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mBtnCaptcha.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            mBtnCaptcha.setText(millisUntilFinished / 1000 + "秒后\n重新获取");
            mBtnCaptcha.setClickable(true);
            mBtnCaptcha.setEnabled(false);
        }

        @Override
        public void onFinish() {
            mBtnCaptcha.setClickable(true);
            mBtnCaptcha.setEnabled(true);
            mBtnCaptcha.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
            mBtnCaptcha.setText("获取验证码");
        }
    };
}
